package com.game.core.dbwrite.domain;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.core.dbwrite.constant.DBOperationType;
import com.game.core.dbwrite.util.WriteToDBUtil;

public class QueueCache
{
	private static final Logger logger = LoggerFactory.getLogger(QueueCache.class);
	private static final Map<Long, StoreEntity> map = new LinkedHashMap<Long, StoreEntity>();
	private static final List<StoreEntity> list = new ArrayList<StoreEntity>();
	private static final ReadWriteLock lock = new ReentrantReadWriteLock(false);

	public QueueCache()
	{
	}

	public static void add(long beanNum, Class<?> clazz, DBOperationType type, byte[] b)
	{
		try
		{
			lock.readLock().lock();
			StoreEntity entity = new StoreEntity(clazz, type, b);
			map.put(beanNum, entity);
			// logger.debug("========= QueueCache add "+type+" :  "+beanNum);
		}
		catch(Exception e)
		{
//			e.printStackTrace();
			logger.error("exception,",e);
		}
		finally
		{
			lock.readLock().unlock();
		}
	}

	public static synchronized void writeToDatabase()
	{
		try
		{
			lock.writeLock().lock();
			Iterator<Entry<Long, StoreEntity>> iter = map.entrySet().iterator();
			while (iter.hasNext())
			{
				Map.Entry<Long, StoreEntity> entry = iter.next();
				list.add(entry.getValue());
				logger.debug("========= QueueCache writeToDatabase " + entry.getKey());
			}
			map.clear();
		}
		catch(Exception e)
		{
//			e.printStackTrace();
			logger.error("exception,",e);
		}
		finally
		{
			lock.writeLock().unlock();
		}
		Iterator<StoreEntity> ite = list.iterator();
		while (ite.hasNext())
		{
			WriteToDBUtil.writeStoreEntityToDB(ite.next());
			ite.remove();
		}
	}

	public static boolean isQueueCacheFinishedWriting()
	{
		return (map.isEmpty() && list.isEmpty());
	}
}